package com.hyfrogx.modules.app.controller.aplipay;


import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradeAppPayModel;
import com.alipay.api.domain.AlipayTradePayModel;
import com.alipay.api.request.AlipayTradeAppPayRequest;
import com.alipay.api.response.AlipayTradeAppPayResponse;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hyfrogx.common.param.JSONResult;
import com.hyfrogx.common.utils.IPUtils;
import com.hyfrogx.common.utils.R;
import com.hyfrogx.common.utils.Terminal;
import com.hyfrogx.config.AliPayConfig;
import com.hyfrogx.modules.app.annotation.Login;
import com.hyfrogx.modules.app.form.alipay.AlipaySignGetForm;
import com.hyfrogx.modules.app.form.alipay.FreeSignGetForm;
import com.hyfrogx.modules.app.utils.ChargePayRecordConstant;
import com.hyfrogx.modules.app.utils.FrogConstant;
import com.hyfrogx.modules.charge.entity.HyCharge;
import com.hyfrogx.modules.charge.service.HyChargeService;
import com.hyfrogx.modules.manage.controller.BaseController;
import com.hyfrogx.modules.manage.entity.HyProductionScaleEntity;
import com.hyfrogx.modules.manage.entity.chargePayRecord.ChargePayRecordEntity;
import com.hyfrogx.modules.manage.service.HyProductionVacuateService;
import com.hyfrogx.modules.manage.service.chargePayRecord.ChargePayRecordService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author: Luo
 * @Date: 2019/12/6 9:53
 * 支付宝支付接口
 */
@Slf4j
@RestController
@RequestMapping("api/alipay")
@Api(value = "ApiAliPayController",tags = {"客户端--支付宝支付接口"})
public class ApiAliPayController extends BaseController {

    Logger logger = LoggerFactory.getLogger("alipay_coin");


    @Autowired
    HyChargeService chargeService;

    @Autowired
    AliPayConfig aliPayConfig;

    @Autowired
    ChargePayRecordService chargePayRecordService;

    @Autowired
    private HyProductionVacuateService hyProductionVacuateService;

    @Login
    @ApiOperation("模板充值")
    @RequestMapping(value = "sign/get", method = RequestMethod.POST)
    public R signGet(@RequestAttribute(value = "userId",required = true) Long uid, @Validated @RequestBody AlipaySignGetForm form){
        HyCharge charge = chargeService.getOne(new QueryWrapper<HyCharge>()
                .eq("id",form.getChargeId()).eq("status", ChargePayRecordConstant.CommonStatus.NORMAL));
        if(charge == null){
            return R.error("充值方式不存在/不可用");
        }

        //实例化支付宝客户端
        AlipayClient alipayClient = new DefaultAlipayClient(aliPayConfig.getOpen_api_domain(),
                aliPayConfig.getAppid(),aliPayConfig.getPrivate_key(), FrogConstant.DateType.JSON,
                FrogConstant.CharSet.utf8,aliPayConfig.getPublic_key(),"RSA2");
        AlipayTradeAppPayRequest request = new AlipayTradeAppPayRequest();
        AlipayTradeAppPayModel model = new AlipayTradeAppPayModel();
        //对一笔交易的具体描述信息。如果是多种商品，请将商品描述字符串累加传给body。
        model.setBody("充值");
        //商品的标题/交易标题/订单标题/订单关键字等。
        model.setSubject("充值");
        //商户网站唯一订单号 订单号是用 用户名加上系统时间毫秒值
        String outTradeNo = uid + "" + System.currentTimeMillis();
        model.setOutTradeNo(outTradeNo);
        //该笔订单允许的最晚付款时间，逾期将关闭交易。取值范围：1m～15d。m-分钟，h-小时，d-天，1c-当天（1c-当天的情况下，无论交易何时创建，都在0点关闭）。
        // 该参数数值不接受小数点， 如 1.5h，可转换为 90m。
        //注：若为空，则默认为15d。
        model.setTimeoutExpress("30m");
        if(!IPUtils.checkIp()){
            model.setTotalAmount(charge.getMoney() + "");
        }else {
            model.setTotalAmount(FrogConstant.fee);
        }
        //销售产品码，商家和支付宝签约的产品码
        model.setProductCode("QUICK_MSECURITY_PAY");
        request.setBizModel(model);
        //回调地址
        request.setNotifyUrl(aliPayConfig.getCallback());
        try {
            ChargePayRecordEntity recordEntity = new ChargePayRecordEntity();
            recordEntity.setUid(uid);
            recordEntity.setOutTradeNo(outTradeNo);
            recordEntity.setTotalAmount(charge.getMoney());
            recordEntity.setCoin(charge.getTotal());
            //recordEntity.setType(form.getType());
            recordEntity.setChargePresentCoin(charge.getPresent());
            recordEntity.setChannel(ChargePayRecordConstant.PayChannel.ZHIFUBAO);
            recordEntity.setStatus(ChargePayRecordConstant.PayStatus.WILL_PAY);
            recordEntity.setTerminal(Terminal.DisplayChannel.android);
            chargePayRecordService.save(recordEntity);
            AlipayTradeAppPayResponse payResponse = alipayClient.sdkExecute(request);
            logger.info(uid + "***" + charge.getMoney() + "***" + new Date() + "***" + "success -----进入带模板id充值"
                    + "充值规则id" + form.getChargeId());

            Map map = new HashMap();
            map.put("sign",payResponse.getBody());
            map.put("id",recordEntity.getId());

            if(payResponse.isSuccess()){
                return R.ok().put("data",map);
            }else {
                return R.error();
            }
        }catch (AlipayApiException e){
            e.printStackTrace();
            logger.error(uid + "***" + charge.getMoney() + "***" + new Date() + "***" + "fail -----进入带模板id充值"
                    + "充值规则id" + form.getChargeId() + e.getMessage());
            return R.error("支付失败");
        }

    }

    /**
     * 自定义充值获得移动端支付的签名
     *
     * @param uid
     * @return
     */
    @Login
    @ResponseBody
    @ApiOperation("自定义充值模板充值")
    @RequestMapping(value = "custom/sign/get", method = RequestMethod.GET)
    public R freeSignGet(@RequestAttribute(value = "userId",required = true) Long uid, @Validated @RequestBody FreeSignGetForm form) {
        //实例化支付宝客户端
        AlipayClient alipayClient = new DefaultAlipayClient(aliPayConfig.getOpen_api_domain(),
                aliPayConfig.getAppid(), aliPayConfig.getPrivate_key(), FrogConstant.DateType.JSON,
                FrogConstant.CharSet.utf8, aliPayConfig.getPublic_key(), "RSA2");
        AlipayTradeAppPayRequest request = new AlipayTradeAppPayRequest();
        AlipayTradeAppPayModel model = new AlipayTradeAppPayModel();
        //对一笔交易的具体描述信息。如果是多种商品，请将商品描述字符串累加传给body。
        model.setBody("充值");
        //商品的标题/交易标题/订单标题/订单关键字等。
        model.setSubject("充值");
        //商户网站唯一订单号 订单号是用 用户名加上系统时间毫秒值
        String outTradeNo = uid + "" + System.currentTimeMillis();
        model.setOutTradeNo(outTradeNo);
        //该笔订单允许的最晚付款时间，逾期将关闭交易。取值范围：1m～15d。m-分钟，h-小时，d-天，1c-当天（1c-当天的情况下，无论交易何时创建，都在0点关闭）。
        // 该参数数值不接受小数点， 如 1.5h，可转换为 90m。
        //注：若为空，则默认为15d。
        model.setTimeoutExpress("30m");
        if (!IPUtils.checkIp()) {
            model.setTotalAmount(form.getPrice() + "");
        } else {
            model.setTotalAmount(FrogConstant.fee);
        }
        //销售产品码，商家和支付宝签约的产品码
        model.setProductCode("QUICK_MSECURITY_PAY");
        request.setBizModel(model);
        //回调地址
        request.setNotifyUrl(aliPayConfig.getCallback());
        //查询充值比例
        HyProductionScaleEntity scaleEntity = hyProductionVacuateService.getOne(new QueryWrapper<HyProductionScaleEntity>()
                .eq("param_key", FrogConstant.SysConfigKey.ANDROID_CHARGE_SCALE));
        try {
            ChargePayRecordEntity recordEntity = new ChargePayRecordEntity();
            recordEntity.setUid(uid);
            recordEntity.setOutTradeNo(outTradeNo);
            recordEntity.setTotalAmount(form.getPrice());
            recordEntity.setCoin(form.getPrice() * scaleEntity.getScale());
            //recordEntity.setType(form.getType());
            recordEntity.setChargePresentCoin(0);
            recordEntity.setChannel(ChargePayRecordConstant.PayChannel.ZHIFUBAO);
            recordEntity.setStatus(ChargePayRecordConstant.PayStatus.WILL_PAY);
            recordEntity.setTerminal(Terminal.DisplayChannel.android);
            chargePayRecordService.save(recordEntity);
            AlipayTradeAppPayResponse payResponse = alipayClient.sdkExecute(request);
            logger.info(uid + "***" + form.getPrice() + "***" + new Date() + "***" + "success -----进入自定义充值" + "充值金额" + form.getPrice());

            Map map = new HashMap();
            map.put("sign", payResponse.getBody());
            map.put("id", recordEntity.getId());
            return R.ok().put("data", map);
        } catch (AlipayApiException e) {
            e.printStackTrace();
            logger.error(uid + "***" + form.getPrice() + "***" + new Date() + "***" + "fail  -----进入自定义充值"
                    + "充值金额" + form.getPrice() + e.getMessage());
            return R.error("支付失败");
        }
    }


    /**
     * 取消支付
     *
     * @param
     * @return
     */
    @Login
    @ApiOperation("取消支付")
    @ResponseBody
    @RequestMapping(value = "cancle/order", method = RequestMethod.POST)
    public R cancleOrderById(Integer id) {
        try {
            ChargePayRecordEntity payRecordEntity = new ChargePayRecordEntity();
            payRecordEntity.setStatus(ChargePayRecordConstant.PayStatus.CANCEL);
            payRecordEntity.setId(id);
            chargePayRecordService.updateById(payRecordEntity);
            logger.info("***cancle***" + id + "***" + new Date() + "***" + "success");
            return R.ok();
        } catch (Exception e) {
            logger.info( "***cancle***" + id + "***" + new Date() + "***" + "fail" + e.getMessage());
            return R.error(e.getMessage());
        }
    }
}
